<template>
  <div>
    <!-- 索赔工时单价历史查询-->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="90" @filterChange="changeHandle"  @resetChange="resetHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :onRowSelectChange="selectChange"
    >
      <template slot="controls" slot-scope="props">
<!--        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>-->
        <!-- <multiuse-button size="small" type="primary" :click="block.bind()" >下发</multiuse-button> -->
        <multiuse-button size="small" type="primary" :click="downloadTemplate.bind()">导出模板</multiuse-button>
        <multiuse-button size="small" type="primary" @click="showImportFun()">数据导入</multiuse-button>
<!--        <multiuse-button size="small" type="primary" @click="issue()">下发</multiuse-button>-->
<!--        <multiuse-button size="small" type="primary" @click="queryClaimHistory()">索赔工时历史查询</multiuse-button>-->
        <multiuse-button type="primary" @click="downloadTemplate2()">导出</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="emitVisible" title="索赔工时单价编辑" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddForm @close="emitCloseHandle" @save="emitChange" :rowData="rowData"/>
    </BaseDialog>
    <BaseDialog :visible.sync="selectDelearFlag" :title="'服务中心选择'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple"></DealerList>
    </BaseDialog>
    <BaseDialog :visible.sync="queryHistory" title="索赔工时历史查询" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryHistory @close="close2()" @click="queryClaimHistory()" :rowData="rowData"/>
    </BaseDialog>

    <BaseDialog
      :visible.sync="showImport"
      :closable="false"
      icon="el-icon-upload"
      title="导入"
      width="800px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <importExcel @close="showImport = false" @importclose="editsave()" :url="`${uploadUrl}/api/cms_claimfac/tmClaimLabourPrice/importExcel`" />
    </BaseDialog>
  </div>
</template>
<script>
import { getListByPage,downloadModel,claimFullRelease,getCarModels,getListForExport } from '@/api/claim/factory/LaborHourPrice';
import { exportExcelFile } from '@/utils/index';
import importExcel from './importExcel';
import { getCarSeries } from '@/api/claim/factory/GenerallyCarPartTypeWarrantyMaintain';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { dictionary } from '@/utils/dictMixin';
import config from '@/assets/js/config';
import AddForm from './AddForm.vue';
import queryHistory from './queryHistory.vue';
export default {
  mixins: [dictionary],
  components: { AddForm, importExcel ,DealerList ,queryHistory},
  data() {
    return {
      collapse: false,
      fetchapi: getListByPage,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      selectDelearFlag: false,
      queryHistory:false,
      dealerData: [],
      selectClaimLabour:[],//选中的工时单价
      rowData:{},
      emitVisible: false,
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      disableds: true,
      showImport: false,
      formData: {},
      actions: { type: '', title: '', visible: false, data: null },
      uploadUrl: config.uploadUrl,
    };
  },
  created() {
    this.getCarModelData();
  },
  methods: {
    close2(){
      this.queryHistory = false
    },
    getCarModelData() {
       this.topFilterInit.find(item => item.fieldName === 'modelCode').initialValue = '';
       let dataArr = [];
      getCarModels().then(res => {
        if (res.resultCode === 200){
          res.data.forEach((item) =>{
            this.topFilterInit.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({ text: x.MODEL_CODE1, value: x.MODEL_CODE1 }));
            dataArr.push({ text: item.MODEL_CODE1, value: item.MODEL_CODE1 })
          })
        }
      });
       this.modelList = dataArr;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ?  this.selectDealerData : null}, { xhrAbort: false });
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
      let params = { ...this.fetchParams };
      console.log("params111",params)
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '车型代码',
          fieldName: 'modelCode',
          placeholder: '请选择...',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '服务考评结果',
          fieldName: 'result',
          placeholder: '请输入服务考评结果...',
          initialValue: '',
          itemList: this.createDictList('5519'),
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'status',
          placeholder: '请输入状态...',
          itemList: [{text: '启用', value: 0},{text: '待启用', value: 1}]
        },
        {
          type: 'INPUT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 60,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          minWidth: '110',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.emitFun(props.row)}>
                  编辑
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.queryClaimHistory(props.row)}>
                  历史记录
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '服务中心代码',dataIndex: 'ownerCode', sorter: true },
        { title: '服务中心名称', dataIndex: 'ownerName', sorter: true },
        { title: '车型代码', dataIndex: 'modelCode', sorter: true },
        {
          title: '服务考评结果',
          dataIndex: 'result',
          sorter: true,
          render: (props) => {
            return (
              <span>
                {
                  this.createDictText(props.row.result, "5519")
                }
              </span>
            );
          },
        },
        {
          title: '考评系数',
          dataIndex: 'modulus',
          sorter: true ,
          render: (props) => {
            return (
              <span>
                {
                  this.createDictText(props.row.modulus, "5520")
                }
              </span>
            );
          },
        },
        { title: '索赔基数', dataIndex: 'base', sorter: true },
        { title: '索赔工时单价',  dataIndex: 'labourPrice', sorter: true },
        { title: '计划索赔工时单价',dataIndex: 'labourPricePlan', sorter: true },
        { title: '状态', dataIndex: 'statusStr', sorter: true },
        { title: '生效日期',  dataIndex: 'validDate', sorter: true },
        { title: '创建人', dataIndex: 'createdBy', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', sorter: true },
        { title: '修改人', dataIndex: 'updatedBy', sorter: true },
        { title: '修改时间', dataIndex: 'updatedAt', sorter: true }
      ];
    },
    emitFun(data,type) {

      if (data.modulus===""){
        data.modulus = null;
      }else {
        data.modulus = Number(data.modulus)
      }
      if (data.result===""){
        data.result = null;
      }else {
        data.result =  Number(data.result)
      }
      this.rowData = data;
      console.log("data",data)
      this.emitVisible = true;
      this.actions = { type: 'edit', visible: true, title: '索赔工时单价编辑' };
    },
    emitCloseHandle() {
      this.emitVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    emitChange() {
      this.emitVisible = true;
      this.fetchParams = { ...this.fetchParams };
    },
    add() {
      this.actions = { type: 'add', visible: true, title: '索赔工时单价新增' };
    },
    //导出
    async downloadTemplate2() {
      let [err, formData] = await this.$refs.TopFilterss.GET_FORM_DATA();
      console.log('formData',formData)
      this.fetchParams = Object.assign({}, this.fetchParams, { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ?  this.selectDealerData : null}, { xhrAbort: false });

      let params = { ...this.fetchParams };
      console.log("params222",params)
      if(!err){
        getListForExport(params).then(res => {
          exportExcelFile(res.data, '索赔工时单价维护');
        });
      }
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        downloadModel().then((res) => {
          console.log(res);
          exportExcelFile(res.data, '索赔工时单价维护导入模板');
        });
      });
    },
    async close(val) {
      this.actions.visible = val;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    editsave() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    // 历史查询
    queryClaimHistory(data) {
      this.rowData = data;
      this.queryHistory = true;
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
    },
    //下发
    async issue(){
      const res = await claimFullRelease();
      if (res.resultCode === 200) {
          this.$notify.success({ type: '提示信息', message: '操作成功!!' });
          this.close();
      }
    }
  },
};
</script>

<style lang="less" scoped></style>
